<template>
  <div>
    <zm-form :model="form" :rules="formRuleTwo" ref="zmForm" label-width="150px">
      <div v-if="!form.productId">
        <zm-form-item prop="productId" label="关联产品">
          <zm-button size="mini" class="ml5" @click="goSelect">
            {{ form.productId ? '重新选择' : '选择产品' }}
          </zm-button>
        </zm-form-item>
        <div class="tc mt80">
          <div><i class="el-icon-box" style="font-size:60px;"></i></div>
          <div class="mt20">暂无选择销售产品</div>
        </div>
      </div>
      <div v-if="form.productId">
        <div class="fb fs16 mb20 pl50">产品信息</div>
        <zm-form-item prop="productId" label="关联产品">
          <zm-button size="mini" class="ml5" @click="goSelect">
            {{ form.productId ? '重新选择' : '选择产品' }}
          </zm-button>
        </zm-form-item>
        <zm-form-item prop="productCode" label="产品编号">
          <span>{{ form.productCode }}</span>
        </zm-form-item>
        <zm-form-item prop="productName" label="产品名称">
          <span>{{ form.productName }}</span>
        </zm-form-item>
        <!-- 日常销售单,特殊销售单,客情销售单,客诉销售单时才展示--翠娟2022-09-01-->
        <div v-if="showGiveBind">
          <zm-form-item prop="isGive" label="转赠配置">
            <zm-data-radio v-model="form.isGive" k1="GIVE_STATUS" />
            <tip
              content="若配置为可转赠，转赠不限制次数，可无限次进行转赠，若卡券已经被使用则无法进行转赠操作"
            ></tip>
          </zm-form-item>
          <zm-form-item prop="isUnbundling" label="解绑配置">
            <zm-data-radio v-model="form.isUnbundling" k1="UNBIND_STATUS" />
          </zm-form-item>
          <zm-form-item label="配置卡面" prop="cardSurfaceImage" v-if="form.productType == '3'">
            <zm-button type="primary" @click="onCardSurface">配置</zm-button>
            <p class="tip-card">若未配置,则使用默认卡面</p>
            <!--             <zm-image-upload
              class="image-preview"
              style="width:450px !important"
              v-if="form.cardSurfaceImage"
              v-model="form.cardSurfaceImage"
              @on-remove="handleDelImage"
              :limit="1"
            ></zm-image-upload> -->
            <div class="image-pre" v-show="form.cardSurfaceImage">
              <el-image
                ref="imagePreview"
                :src="form.cardSurfaceImage"
                style="width: 380px; height: 200px; border-radius: 16px;"
                fit="cover"
                :preview-src-list="[form.cardSurfaceImage]"
              >
              </el-image>
              <div class="delete-img">
                <div class="fixed-img">
                  <i style="margin-right: 20px;" class="el-icon-search" @click="handlePreview"></i>
                  <i class="el-icon-delete" @click="handleDelImage"></i>
                </div>
              </div>
            </div>
          </zm-form-item>
          <!-- 点卡的时候提交该字段 -->
          <zm-form-item prop="isOpenRecharge" label="是否开放充值" v-if="form.productType === '3'">
            <zm-data-radio class="isOpenRecharge" v-model="form.isOpenRecharge" k1="IS_TYPE" />
          </zm-form-item>
          <zm-form-item v-if="showRepair" prop="isCashDiff" label="是否开放现金补差">
            <zm-data-radio
              :disabled="form.type === '1'"
              v-model="form.isCashDiff"
              k1="CARD_REPAIR_STATUS"
            />
            <tip content="开放现金补差，则前台按订单维度扣除卡余额后进行补差"></tip>
          </zm-form-item>
        </div>
        <div class="fb fs16 mtb20 pl50">销售信息</div>
        <zm-form-item
          prop="couponProductId"
          label="选择次卡绑定产品"
          v-if="form.productType === '4'"
        >
          <zm-data-select
            v-model="form.couponProductId"
            :list="frequencyCardProductList"
            @change="selectCikaProduct"
            class="w300"
          />
        </zm-form-item>
        <zm-form-item prop="saleType" label="售货方式">
          <zm-data-select
            v-model="form.saleType"
            :list="saleTypeList"
            placeholder="请选择"
            class="w300"
          />
        </zm-form-item>
        <!-- 点卡独有的几个配置项 -->
        <zm-form-item prop="saleScalePrice" label="销售比例" v-if="form.productType === '3'">
          <zm-input
            v-model="form.saleScalePrice"
            @change="changeCustomerize"
            :disabled="rateDisabled"
            class="w100"
          ></zm-input>
          <span>:</span>
          <zm-form-item prop="saleScalePoint" class="dib mb0">
            <zm-input
              v-model="form.saleScalePoint"
              @change="changeCustomerize"
              :disabled="rateDisabled"
              class="w100"
            ></zm-input>
          </zm-form-item>
          <tip
            content="日常销售单无法修改销售比例，如有特殊有效期需求，请走特殊销售单"
            v-if="form.type === '1'"
          ></tip>
        </zm-form-item>
        <zm-form-item prop="consumptionScalePrice" label="消费比例" v-if="form.productType === '3'">
          <zm-input
            v-model="form.consumptionScalePrice"
            :disabled="rateDisabled"
            class="w100"
          ></zm-input>
          <span>:</span>
          <zm-form-item prop="consumptionScalePoint" class="dib mb0">
            <zm-input
              v-model="form.consumptionScalePoint"
              :disabled="rateDisabled"
              class="w100"
            ></zm-input>
          </zm-form-item>
          <tip
            content="日常销售单无法修改消费比例，如有特殊有效期需求，请走特殊销售单"
            v-if="form.type === '1'"
          ></tip>
        </zm-form-item>
        <zm-form-item prop="isCustomize" label="点卡销售" v-if="form.productType === '3'">
          <zm-data-radio v-model="form.isCustomize" :list="isCustomizeList" />
        </zm-form-item>
        <!-- 点卡销售选择自定义金额时的配置 -->
        <zm-form-item
          prop="customizePrice"
          v-if="form.productType === '3' && form.isCustomize === '1'"
        >
          <div v-for="(item, index) in form.customizePrice" :key="index">
            <div class="dib mr10">金额{{ index + 1 }}</div>
            <zm-form-item
              :prop="getProp(index, 'unitPrice')"
              :rules="getRules('unitPrice')"
              class="dib"
            >
              销售单价：<zm-input
                v-model="item.unitPrice"
                @change="getCustomerize(item)"
                class="w80"
              ></zm-input>
              <span class="ml5">元，</span>
            </zm-form-item>
            <zm-form-item class="dib">
              <span
                >产品面值：内含{{ item.unitPrice || '--' }}元，折合卡内点数{{
                  item.unitPoint || '--'
                }}点，
              </span>
            </zm-form-item>
            <zm-form-item :prop="getProp(index, 'num')" :rules="getRules('num')" class="dib">
              数量：<zm-input
                v-model="item.num"
                @change="getCustomerize(item)"
                class="w80"
              ></zm-input>
              <span class="ml5">张，</span>
            </zm-form-item>
            <zm-form-item
              :prop="getProp(index, 'totalPrice')"
              :rules="getRules('totalPrice')"
              class="dib"
            >
              总额：<zm-input v-model="item.totalPrice" @change="getSaleTotalPrice" class="w80">
              </zm-input>
              <span class="ml5">元</span>
            </zm-form-item>
            <zm-button type="text" @click="addPrice">新增</zm-button>
            <zm-button type="text" @click="deletePrice(index)" v-if="index > 0">
              删除
            </zm-button>
          </div>
        </zm-form-item>
        <zm-form-item
          prop="salePrice"
          label="销售单价"
          v-if="
            form.productType === '1' ||
              form.productType === '2' ||
              (form.productType === '3' && form.isCustomize === '0') ||
              form.productType === '5'
          "
        >
          <zm-input
            v-model="form.salePrice"
            @change="getSaleTotalPrice"
            :placeholder="
              form.productType === '3'
                ? '请输入卡面值，卡内实际可用金额'
                : '请输入产品销售单价，建议不低于产品成本'
            "
            class="w300"
          >
            <span slot="append">元</span>
          </zm-input>
          <tip
            content="日常销售单，销售单价建议不低于成本价，如有需求请走特殊销售单"
            v-if="form.type === '1'"
          ></tip>
        </zm-form-item>
        <zm-form-item prop="couponPrice" label="销售单价" v-if="form.productType === '4'">
          <div class="dib">
            <zm-input
              v-model="form.couponPrice"
              placeholder="请输入券销售单价"
              @change="getSaleTotalPrice"
              class="w300"
            >
              <span slot="append">元</span>
            </zm-input>
          </div>
          <zm-form-item prop="couponNumber" class="dib mb0 ml5">
            <span>单张次卡内含</span>
            <zm-input
              v-model="form.couponNumber"
              placeholder="请输入张数"
              @change="getSaleTotalPrice"
              class="w200"
            >
              <span slot="append">张</span>
            </zm-input>
          </zm-form-item>
          <span class="ml5">单张次卡销售单价¥{{ form.cikaSalePrice }}</span>
          <tip content="日常销售单，销售单价建议不低于成本价，如有需求请走特殊销售单"></tip>
        </zm-form-item>
        <zm-form-item label="优惠面值" v-if="form.productType === '5'">
          <span>{{ form.discountPriceName }}</span>
        </zm-form-item>
        <zm-form-item
          prop="parValue"
          label="产品面值"
          v-if="form.productType !== '3' && form.productType !== '5'"
        >
          <zm-input v-model="form.parValue" :disabled="form.type === '1'" class="w300">
            <span slot="append">元</span>
          </zm-input>
        </zm-form-item>
        <zm-form-item label="产品面值" v-if="form.productType === '3' && form.isCustomize !== '1'">
          <span>{{
            '内含' + (form.salePrice || 0) + '元,折合卡内点数' + diankaParValueName + '点'
          }}</span>
          <span v-if="discountPrice != 0"
            >最高膨胀点数{{ diankaParValueName * discountPrice }}点</span
          >
        </zm-form-item>
        <zm-form-item prop="number" label="数量" v-if="form.isCustomize !== '1'">
          <zm-input
            v-model="form.number"
            @change="getSaleTotalPrice"
            placeholder="请输入销售数量"
            class="w300"
          >
            <span slot="append">张</span>
          </zm-input>
        </zm-form-item>
        <!-- 销售单总额要计算初始值 -->
        <!-- 销售单总额都为单价x数量，点卡的自定义金额单独计算 -->
        <zm-form-item prop="computedTotal" label="销售单总额">
          <!--    form.type === '3' || form.type === '5' || -->
          <zm-input
            v-model="form.computedTotal"
            placeholder="请输入销售单总额"
            class="w300"
            @blur="inputTotal"
            :disabled="
              (form.type === '1' && form.productType !== '3') ||
                (form.productType === '3' && form.isCustomize === '1')
            "
          >
            <span slot="append">元</span>
          </zm-input>
          <tip
            content="日常销售单无法修改销售单总额，如有特殊需求，请走特殊销售单"
            v-if="form.type === '1' && form.productType !== '3'"
          ></tip>
        </zm-form-item>
        <zm-form-item
          prop="productExpiredDays"
          label="产品有效天数"
          v-if="form.type !== '3' && form.type !== '5'"
        >
          <span class="text-error">{{ form.productExpiredDays }}天</span>
        </zm-form-item>
        <zm-form-item prop="expiredType" label="有效期类型">
          <zm-data-radio
            v-model="form.expiredType"
            :list="expiredTypeList"
            @change="changeExpiredType"
          />
        </zm-form-item>
        <!-- 有效期三种情况需要重新过一下判断，优化下代码 -->
        <zm-form-item
          prop="startDate"
          label="有效期"
          v-if="form.type === '1' && form.expiredType === '1'"
        >
          <!-- <zm-date-picker :start-date.sync="form.startDate" :end-date.sync="form.endDate" type="daterange" date-class="w300" class="vm" :show-radio="false" size="mini" @change="changeDate">
          </zm-date-picker> -->
          <zm-date-picker
            :start-date.sync="form.startDate"
            :end-date.sync="form.endDate"
            type="date"
            time-part
            date-class="w150"
            class="vm"
            :show-radio="false"
            size="mini"
            @change="changeDate"
          />
          <!-- <span>{{
            form.endComputedDate
              ? "至" + form.endComputedDate
              : "至xxxx年xx月xx日"
          }}</span> -->
          <tip content="有效期只可配置在产品配置的有效期范围内"></tip>
        </zm-form-item>
        <zm-form-item label="有效期" v-if="form.type === '1' && form.expiredType === '2'">
          <span
            >绑定成功后<span class="text-error">{{ form.productExpiredDays || '--' }}</span
            >天有效</span
          >
        </zm-form-item>
        <zm-form-item
          prop="endDate"
          label="有效期"
          v-if="form.type !== '1' && form.expiredType === '1'"
        >
          <zm-date-picker
            :start-date.sync="form.startDate"
            :end-date.sync="form.endDate"
            type="date"
            time-part
            date-class="w150"
            class="vm"
            :show-radio="false"
            size="mini"
          />
        </zm-form-item>
        <zm-form-item
          prop="floatDay"
          label="有效期"
          v-if="form.type !== '1' && form.expiredType !== '1'"
        >
          <span>{{ form.expiredType === '2' ? '绑定成功后' : '成功销售后' }}</span>
          <zm-input v-model="form.floatDay" class="w200"></zm-input>
          <zm-form-item prop="floatUnit" class="dib">
            <zm-data-select v-model="form.floatUnit" :list="unitList" class="w100" />
          </zm-form-item>
          <span>有效</span>
        </zm-form-item>
        <zm-form-item
          prop="proportion"
          label="提成比例"
          v-if="form.type !== '3' && form.type !== '5'"
        >
          <!-- <span>{{
            form.proportion ? hundredProportion : "请匹配正确的提成比例"
          }}</span> -->
          <zm-input
            v-model="form.proportion"
            class="w200"
            @blur="getProportionPrice"
            :disabled="$route.name !== 'approvalMgr'"
          >
            <span slot="append">%</span>
          </zm-input>
          <!-- <span>请匹配正确的提成比例</span> -->
          <tip
            content="若有特殊提成比例，请在备注信息中标注，审批中可修改此比例并按此生效（建议提前确认）"
          ></tip>
        </zm-form-item>
        <zm-form-item
          prop="proportionPrice"
          label="预估提成"
          v-if="form.type !== '3' && form.type !== '5'"
        >
          <span>¥{{ form.proportionPrice }}</span>
        </zm-form-item>
        <zm-form-item prop="cardSaleScale" label="销售折扣" v-if="form.productType === '3'">
          <span>{{ form.cardSaleScale + '%' }}</span>
        </zm-form-item>
        <zm-form-item prop="remark" label="备注信息">
          <zm-input
            v-model="form.remark"
            type="textarea"
            :maxlength="300"
            placeholder="请输入备注信息"
            class="w500"
            :disabled="isApprove"
          >
          </zm-input>
        </zm-form-item>
      </div>
    </zm-form>
    <!-- 销售产品-选择产品弹框 -->
    <select-product
      v-if="selectVisible"
      v-model="selectVisible"
      :product-info="form"
      @after-select="afterSelect"
    >
    </select-product>
    <!-- 卡面配置弹框 -->
    <select-surface-image
      v-if="showCardSurfaceImage"
      v-model="showCardSurfaceImage"
      :card-surface-image="form.cardSurfaceImage"
      @handle-after="selectSurfaceCallBack"
    ></select-surface-image>
  </div>
</template>

<script>
import { formRuleTwo, saleTypeList, unitList, isCustomizeList, rulesCustomizePrice } from '../const'
import SelectProduct from './SelectProduct'
import Tip from '@/components/Tip'
import SelectSurfaceImage from '@/components/SelectSurfaceImage'
import dayjs from 'dayjs'
import saleOrderApi from '@/api/src/saleOrder'
import productApis from '@/api/src/product'
import productDraftApis from '@/api/src/productDraft'
import publicApis from '@/api/src/public'
import { judgeArrFill } from '@/utils'
import datePickerMixin from '@/mixins/datePickerMixin'
import zmDatePicker from '@/components/ZmDatePicker'
import cardSurface from '@/api/src/cardSurface'
import ZmImageUpload from '@/components/ZmUpload/components/ImageUpload.vue'

export default {
  components: { SelectProduct, ZmImageUpload, Tip, zmDatePicker, SelectSurfaceImage },
  mixins: [datePickerMixin],
  props: {
    value: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      cardSurfaceList: [], // 卡面数组
      discountPrice: 0,
      saleScalePoint: 0,
      formRuleTwo,
      saleTypeList,
      unitList,
      isCustomizeList,
      selectVisible: false,
      rulesCustomizePrice,
      frequencyCardProductList: [],
      showCardSurfaceImage: false
    }
  },
  computed: {
    form: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    showRepair() {
      return ['1', '2', '3', '5'].includes(this.form.type) && this.form.productType === '3'
    },
    showGiveBind() {
      return ['1', '2', '3', '5'].includes(this.form.type)
    },
    expiredTypeList() {
      let list = [
        {
          name: '固定有效期',
          value: '1'
        },
        {
          name: '按绑定后生效',
          value: '2'
        },
        {
          name: '按销售后生效',
          value: '3'
        }
      ]
      if (this.form.type === '1') {
        return list.filter((i) => i.value !== '3')
      } else if (this.form.type !== '1' && this.form.productType !== '3') {
        return list
      } else {
        return list.filter((i) => i.value !== '3')
      }
    },
    hundredProportion() {
      return +this.form.proportion + '%'
    },
    rateDisabled() {
      if (this.form.productType === '3' && this.form.type !== '2') {
        return true
      } else {
        return false
      }
    },
    diankaParValueName() {
      let par = (+this.form.saleScalePoint / +this.form.saleScalePrice) * +this.form.salePrice
      if (!isFinite(par)) {
        return 0
      } else {
        return par.toFixed(2)
      }
    },
    isApprove() {
      return this.$route.name === 'approvalMgr'
    }
  },
  watch: {
    'form.productExpiredDays'(val) {
      if (val) {
        this.$refs.zmForm.validateField('productExpiredDays')
      }
    },
    'form.proportion'(val) {
      if (val) {
        this.$refs.zmForm.validateField('proportion')
      }
    },
    'form.salePrice'(val) {
      // 新需求 【ID1007287】
      if (
        this.form.type === '1' &&
        this.form.productType !== '3' &&
        this.form.productType !== '5'
      ) {
        this.$set(this.form, 'parValue', val)
      }
    },
    'form.couponPrice'(val) {
      // 新需求 【ID1007287】
      if (this.form.type === '1' && this.form.productType === '4') {
        this.$set(this.form, 'parValue', val)
      }
    },
    'form.productId'() {
      this.getCardRule()
    }
  },
  created() {
    this.form.remark = '销售备注'
    if (!this.form.cardSurfaceImage) {
      this.getCardImageList()
    }
  },
  methods: {
    // 获取卡面配置数组
    async getCardImageList() {
      cardSurface.getList().then((res) => {
        this.cardSurfaceList = res
      })
      // this.cardSurfaceList = await cardSurface.getList()
      // if (this.cardSurfaceImage) {
      //   this.cardSurfaceList.forEach((item, index) => {
      //     if (item.iamge === this.cardSurfaceImage) {
      //       this.currentCardIndex = index
      //     }
      //   })
      // }
    },
    getProp(index, label) {
      return `customizePrice[${index}].${label}`
    },
    getRules(label) {
      return this.rulesCustomizePrice.filter((i) => i.label === label)[0].rules
    },
    inputTotal() {
      this.getExpiredDay()
    },
    goSelect() {
      this.selectVisible = true
    },
    onCardSurface() {
      this.showCardSurfaceImage = true
    },
    selectSurfaceCallBack(val) {
      console.log(val)
      this.$set(this.form, 'cardSurfaceImage', val)
    },
    async getFrequencyCardProductList(info) {
      const _res = await publicApis.getFrequencyCardProductList({
        frequencyCardId: info.productId
      })
      this.frequencyCardProductList = _res
    },
    async getCardRule() {
      console.log(this.form)
      if (this.form.productId && this.form.productType === '3') {
        const res = await productDraftApis.getInfo({ id: this.form.productId })
        console.log(res, '==============')
        const xxRule = res.xxRule
        if (xxRule.length) {
          // 高抵
          xxRule.sort((a, b) => {
            return b.discountPrice / b.advancePrice - a.discountPrice / a.advancePrice
          })
          this.discountPrice = xxRule[0].discountPrice / xxRule[0].advancePrice
        }
      }
    },
    // 销售产品-选择产品成功回调
    async afterSelect(productInfo) {
      let info = JSON.parse(JSON.stringify(productInfo))
      if (info.productType === '4') {
        // 次卡
        this.getFrequencyCardProductList(info)
      }
      if (info.productType === '3') {
        // 点卡
        const res = await productDraftApis.getInfo({ id: info.productId })
        if (res.cardSurfaceId) {
          const item = this.cardSurfaceList.find((item) => {
            return item.id === res.cardSurfaceId
          })
          if (item && item.image) {
            this.form.cardSurfaceImage = item.image
          }
          console.log(item, 'item')
        }
        const xxRule = res.xxRule
        if (xxRule.length) {
          // 高抵
          xxRule.sort((a, b) => {
            return b.discountPrice / b.advancePrice - a.discountPrice / a.advancePrice
          })
          this.discountPrice = xxRule[0].discountPrice / xxRule[0].advancePrice
          console.log(this.discountPrice, xxRule[0])
        }
      }
      // productType 1兑换券，2卖品券，3点卡，4次卡，5优惠券
      this.form = {
        ...this.form,
        ...info,
        isCustomize: '0',
        couponProductId: '',
        customizePrice: [
          {
            unitPrice: '',
            unitPoint: '',
            num: '',
            totalPrice: ''
          }
        ]
      }
      console.log(this.form, '===form')
      this.$nextTick(() => {
        this.getSaleTotalPrice()
        this.$refs.zmForm.validateField('productId')
      })
    },
    getProportionPrice() {
      // 计算提成比例和预估提成
      let proportionPrice = (+this.form.computedTotal * +this.form.proportion * 0.01).toFixed(2)
      this.$set(this.form, 'proportionPrice', proportionPrice)
    },
    getExpiredDay() {
      // 1兑换券，2卖品券，3点卡，4次卡，5优惠券
      // if(this.form.productType === '3') {
      // 所有类型下的点卡
      // }
      let params
      let cardSaleScale
      if (this.form.productType === '3' && this.form.isCustomize === '1') {
        // 点卡自定义
        let noFill = judgeArrFill(this.form.customizePrice)
        let ride = this.form.customizePrice.map((i) => {
          return (+i.unitPrice * +i.num).toFixed(2)
        })
        let rideTotal = ride.reduce((n, m) => n + m)
        let total = this.form.customizePrice.map((i) => +i.totalPrice)
        let totalPrice = total.reduce((n, m) => n + m)
        let num = this.form.customizePrice.map((i) => +i.num)
        let totalNum = num.reduce((n, m) => n + m)
        if (!noFill || noFill.length === 0) {
          params = {
            id: this.form.productId,
            scale: totalPrice / rideTotal,
            number: totalNum,
            saleTotalPrice: this.form.computedTotal
          }
          cardSaleScale = (totalPrice / rideTotal).toFixed(2)
        } else {
          params = {
            id: this.form.productId,
            scale: '',
            number: totalNum,
            saleTotalPrice: this.form.computedTotal
          }
          cardSaleScale = 0 // *************待确认******************
        }
      } else if (this.form.productType === '4') {
        params = {
          id: this.form.couponProductId,
          salePrice: this.form.couponPrice,
          number: +this.form.couponNumber * +this.form.number,
          saleTotalPrice: this.form.computedTotal
        }
      } else {
        params = {
          id: this.form.productId,
          number: this.form.number,
          salePrice: this.form.salePrice,
          saleTotalPrice: this.form.computedTotal
        }
        cardSaleScale = (
          +this.form.computedTotal /
          (+this.form.salePrice * +this.form.number)
        ).toFixed(2)
      }
      this.form.cardSaleScale = !isFinite(+cardSaleScale) ? 0 : (+cardSaleScale * 100).toFixed(2)
      if (Object.keys(params).filter((i) => !params[i]).length > 0) {
        console.log('参数有空值')
      } else if (this.form.type !== '3' && this.form.type !== '5') {
        saleOrderApi
          .getProductExpiredDays(params)
          .then((_res) => {
            console.log(_res, 'rrrrrrrrrrrrrr')
            this.$set(this.form, 'productExpiredDays', _res.day)
            if (this.form.type === '2' && this.form.expiredType === '1') {
              // 新需求 【ID1007171】
              let endTime = dayjs()
                .add(+_res.day - 1, 'day')
                .format('YYYY-MM-DD')
              this.$set(this.form, 'startDate', dayjs().format('YYYY-MM-DD'))
              this.$set(this.form, 'endDate', endTime)
            } else if (this.form.type === '1' && this.form.expiredType === '1') {
              // 新需求【ID1007188】
              this.$set(this.form, 'startDate', dayjs().format('YYYY-MM-DD'))
            }
            this.changeDate()
            this.$set(this.form, 'proportion', _res.proportion)
            this.getProportionPrice()
          })
          .catch(() => {
            this.$set(this.form, 'productExpiredDays', '')
            this.$set(this.form, 'proportion', '')
            this.$set(this.form, 'proportionPrice', '')
          })
      }
    },

    async selectCikaProduct(val) {
      // 选择次卡绑定产品后获取产品详情
      const _res = await productApis.getInfo({ id: val })
      this.form = {
        ...this.form,
        parValue: _res.parValue,
        practiceCostPrice: _res.practiceCostPrice,
        theoryCostPrice: _res.theoryCostPrice
      }
      this.getExpiredDay()
    },
    changeDate() {
      this.form.endComputedDate =
        this.form.productExpiredDays && this.form.startDate
          ? dayjs(this.form.startDate)
              .add(+this.form.productExpiredDays - 1, 'day')
              .format('YYYY-MM-DD')
          : ''
    },
    changeExpiredType(val) {
      // 切换清空有效期数据
      this.$set(this.form, 'startDate', '')
      this.$set(this.form, 'endDate', '')
      // 新需求 【ID1007171】
      if (val !== '1' && this.form.type === '2' && this.form.productExpiredDays) {
        this.$set(this.form, 'floatDay', this.form.productExpiredDays)
      }
    },
    getSaleTotalPrice() {
      let total
      if (this.form.productType === '4') {
        // 次卡
        this.form.cikaSalePrice = +this.form.couponNumber * +this.form.couponPrice + ''
        total = +this.form.cikaSalePrice * +this.form.number
      } else if (this.form.productType === '3' && this.form.isCustomize === '1') {
        // 点卡 且选择自定义
        let arr = this.form.customizePrice.map((item) => +item.totalPrice)
        total = arr.reduce((n, m) => n + m)
      } else {
        total = +this.form.salePrice * +this.form.number
      }
      this.$set(this.form, 'computedTotal', total.toFixed(2) + '')
      // 获取产品有效天数和预估提成
      this.getExpiredDay()
    },
    getCustomerize(item) {
      let unitPoint = (+this.form.saleScalePoint / +this.form.saleScalePrice) * +item.unitPrice
      this.$set(item, 'unitPoint', unitPoint)
      this.$set(item, 'totalPrice', +item.unitPrice * +item.num)
      this.getSaleTotalPrice()
    },
    changeCustomerize() {
      // 销售比例改动时
      this.form.customizePrice &&
        this.form.customizePrice.forEach((item) => {
          item.unitPoint = (+this.form.saleScalePoint / +this.form.saleScalePrice) * +item.unitPrice
        })
    },
    addPrice() {
      let item = {
        unitPrice: '',
        unitPoint: '',
        num: '',
        totalPrice: ''
      }
      this.form.customizePrice.push(item)
    },
    deletePrice(index) {
      this.form.customizePrice.splice(index, 1)
    },
    async handleFormValidate() {
      let _valid = false
      this.$refs.zmForm.validate((valid) => {
        _valid = valid
      })

      return new Promise((resolve, reject) => {
        _valid ? resolve() : reject('销售产品')
      })
    },
    handleDelImage() {
      this.form.cardSurfaceImage = ''
    },
    handlePreview() {
      this.$refs.imagePreview.showViewer = true
      console.log((this.$refs.imagePreview.showViewer = true))
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/.el-radio {
  width: 100px;
}
.tip-card {
  color: #cbcbcb;
  font-size: 14px;
  padding: 12px 0;
}
.image-pre {
  position: relative;
  width: 380px;
  border-radius: 12px;
  .delete-img {
    display: none;
  }
  &:hover {
    .delete-img {
      border-radius: 12px;
      display: block;
      position: absolute;
      width: 380px;
      height: 200px;
      line-height: 40px;
      left: 0;
      top: 0;
      background: rgba(59, 60, 61, 0.5);
      box-sizing: content-box;
      z-index: 999;
      cursor: pointer;
      text-align: right;
      .fixed-img {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        margin: 8px 10px 0 0;
        display: block;
        font-size: 24px;
        color: white;
      }
    }
  }
}
.image-preview {
  /deep/.is-success {
    width: 280px !important;
  }
}
</style>
